// pages/user/message-list/message-list.ts
import { messageSystem, getMsgDetails, msgLookDel } from '../../../api/user.js';
import { checkLogin } from '../../../libs/login';
import { goToPage, PAGE_LOGIN } from '../../../config/pages';

interface MessageItem {
  id: number;
  uid: number;
  mark: string;
  title: string;
  content: string;
  type: number;
  look: number;
  is_del: number;
  add_time: string;
  data: string;
}

Page({
  data: {
    messages: [] as MessageItem[],
    loading: false,
    refreshing: false,
    page: 1,
    limit: 10,
    hasMore: true,
    isEmpty: false,
  },

  async onLoad() {
    // 检查登录状态
    if (!checkLogin()) {
      goToPage(PAGE_LOGIN, {}, 'reLaunch');
      return;
    }
    await this.loadMessages();
  },

  // 下拉刷新
  async onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true,
      messages: []
    });
    await this.loadMessages();
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  async onReachBottom() {
    if (!this.data.hasMore || this.data.loading) {
      return;
    }
    const nextPage = this.data.page + 1;
    this.setData({ page: nextPage });
    await this.loadMessages(true);
  },

  // 加载消息列表
  async loadMessages(isLoadMore = false) {
    if (this.data.loading) return;

    this.setData({ loading: true });

    try {
      const params = {
        page: this.data.page,
        limit: this.data.limit
      };

      // @ts-ignore
      const res = await messageSystem(params);
      
      if (res && res.data) {
        const newMessages = res.data.list || [];
        const messages = isLoadMore 
          ? [...this.data.messages, ...newMessages]
          : newMessages;

        this.setData({
          messages,
          hasMore: newMessages.length >= this.data.limit,
          isEmpty: messages.length === 0,
          loading: false
        });
        
        console.log('消息列表加载成功:', messages);
      } else {
        this.setData({ 
          loading: false,
          isEmpty: this.data.messages.length === 0 
        });
      }
    } catch (error: any) {
      console.error('加载消息列表失败:', error);
      this.setData({ loading: false });
      
      wx.showToast({
        title: error?.msg || '加载失败',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 查看消息详情（仅标记已读，不跳转）
  async viewMessage(e: any) {
    const { id } = e.currentTarget.dataset;
    
    try {
      // @ts-ignore
      const res = await getMsgDetails(id);
      
      if (res && res.data) {
        // 调用API标记消息为已读，但不跳转到详情页
        // 刷新列表以更新已读状态
        this.loadMessages();
      }
    } catch (error: any) {
      console.error('获取消息详情失败:', error);
      wx.showToast({
        title: error?.msg || '获取详情失败',
        icon: 'none'
      });
    }
  },

  // 删除消息
  async deleteMessage(e: any) {
    const { id } = e.currentTarget.dataset;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条消息吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            // @ts-ignore
            const result = await msgLookDel({
              id: id,
              key: 'is_del',
              value: 1
            });
            
            if (result && result.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              // 从列表中移除该消息
              const messages = this.data.messages.filter(msg => msg.id !== id);
              this.setData({ messages });
            }
          } catch (error: any) {
            console.error('删除消息失败:', error);
            wx.showToast({
              title: error?.msg || '删除失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 全部已读
  async markAllRead() {
    wx.showModal({
      title: '确认操作',
      content: '确定要将所有消息标记为已读吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            // @ts-ignore
            const result = await msgLookDel({
              key: 'look',
              value: 1,
              all: 1
            });
            
            if (result && result.code === 200) {
              wx.showToast({
                title: '操作成功',
                icon: 'success'
              });
              
              // 刷新列表
              this.loadMessages();
            }
          } catch (error: any) {
            console.error('全部已读失败:', error);
            wx.showToast({
              title: error?.msg || '操作失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 全部删除
  async deleteAll() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除所有消息吗？此操作不可恢复！',
      success: async (res) => {
        if (res.confirm) {
          try {
            // @ts-ignore
            const result = await msgLookDel({
              key: 'is_del',
              value: 1,
              all: 1
            });
            
            if (result && result.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              // 清空列表
              this.setData({ messages: [], isEmpty: true });
            }
          } catch (error: any) {
            console.error('全部删除失败:', error);
            wx.showToast({
              title: error?.msg || '删除失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 根据消息类型获取图标
  getMessageIcon(mark: string): string {
    const iconMap: { [key: string]: string } = {
      'order_pay_success': 'fa-credit-card',
      'order_take': 'fa-check-circle',
      'order_refund': 'fa-undo',
      'recharge_success': 'fa-plus-circle',
      'user_extract': 'fa-money-bill-wave',
      'order_brokerage': 'fa-coins',
      'bargain_success': 'fa-handshake',
      'combination_success': 'fa-users',
      'price_revision': 'fa-tag',
      'integral_accout': 'fa-star',
      'user_balance_change': 'fa-wallet'
    };
    
    return iconMap[mark] || 'fa-bell';
  },

  // 格式化时间
  formatTime(timeStr: string): string {
    if (!timeStr) return '';
    
    const time = new Date(timeStr);
    const now = new Date();
    const diff = now.getTime() - time.getTime();
    
    if (diff < 60000) { // 1分钟内
      return '刚刚';
    } else if (diff < 3600000) { // 1小时内
      return Math.floor(diff / 60000) + '分钟前';
    } else if (diff < 86400000) { // 1天内
      return Math.floor(diff / 3600000) + '小时前';
    } else if (diff < 604800000) { // 1周内
      return Math.floor(diff / 86400000) + '天前';
    } else {
      return time.toLocaleDateString();
    }
  }
});

